const http = require('../../utils/http.js');
Page({
    data: {
        base_candidate_info:{
            recognitionResult: '',
            recording: false,  // 用于标记当前是否正在录音
          isPaused: false,   // 用于标记录音是否处于暂停状态
          recordFilePath: '',  // 用于保存录音文件的临时路径
          editableContent: '', // 用于保存识别后文本内容的初始化
          buttonText: '开始录音', // 新增按钮文本控制变量
          },
        id_number:'',
      address: '',
      postalCode: '',
      recipientName: ''
    },
    onLoad(){
        const storaged_post_info = wx.getStorageSync('post_candidate_info');
        this.setData({
            id_number:storaged_post_info.id_number,
            address: storaged_post_info.address,
            postalCode: storaged_post_info.postal_code,
            recipientName: storaged_post_info.recipient_name
        })
    },
    bindAddressInput: function(e) {
      this.setData({
        address: e.detail.value
      });
    },
    bindPostalCodeInput: function(e) {
      this.setData({
        postalCode: e.detail.value
      });
    },
    bindRecipientNameInput: function(e) {
      this.setData({
        recipientName: e.detail.value
      });
    },
    handleSubmit: function() {
      const { address, postalCode, recipientName } = this.data;
      if (!address || !postalCode || !recipientName) {
        wx.showToast({
          title: '请填写所有信息',
          icon: 'none'
        });
        return;
      }

      const postData={
          "id_number" :this.data.id_number,
          address:this.data.address,
          postal_code :this.data.postalCode,
          recipient_name:this.data.recipientName
      }
      http.post('/candidate/updateNotificationInfo', postData).then(res =>{
        if (res.data.code === 200) {
            wx.setStorageSync('post_candidate_info', postData);
            wx.showToast({ title: '邮寄信息更新成功', duration: 3000 });
            wx.switchTab({
              url: '/pages/registration/registration',
            });
          }
      }).catch(err => {
        console.error('邮寄信息更新失败:', err);
        wx.showToast({ title: '邮寄信息更新失败', icon: 'none' });
      });
    },
    checkRecordPermission() {
        return new Promise((resolve, reject) => {
            wx.getSetting({
                success(res) {
                    if (res.authSetting['scope.record']) {
                        console.log('已获取录音权限，直接resolve');
                        resolve();
                    } else {
                        wx.authorize({
                            scope: 'scope.record',
                            success() {
                                console.log('申请录音权限成功，resolve');
                                resolve();
                            },
                            fail() {
                                console.log('申请录音权限失败，reject');
                                reject('用户未授予录音权限');
                            }
                        });
                    }
                },
                fail() {
                    console.log('获取录音权限设置失败，reject');
                    reject('获取录音权限设置失败');
                }
            });
        });
    },
      
    
    
    toggleRecording() {
        const that = this;
        if (that.data.recording) {
            // 停止录音逻辑
            that.setData({ recording: false });
            const recorderManager = wx.getRecorderManager();
            recorderManager.stop();
            recorderManager.onStop((res) => {
                // 将录音文件临时路径存储到本地存储
                wx.setStorageSync('recordPath', res.tempFilePath);
                that.setData({ recordFilePath: res.tempFilePath });
                // 这里调用后端代码进行录音转文字
                // that.setData({ editableContent: '转换后的文本内容' });
                that.setData({ buttonText: '开始录音' });
            });
        } else {
            that.checkRecordPermission().then(() => {
                // 开始录音逻辑
                that.setData({ recording: true });
                const recorderManager = wx.getRecorderManager();
                recorderManager.start({
                    format: 'wav', // 设置为wav格式
                    duration: 60000, 
                    sampleRate: 44100, 
                    numberOfChannels: 1, 
                    encodeBitRate: 96000
                });
                that.setData({ buttonText: '停止录音' });
            }).catch((error) => {
                wx.showToast({
                    title: 'error',
                    icon:'none'
                });
            });
        }
    },
    
    // 上传录音并进行语音识别函数
    uploadAndRecognizeRecording() {
        if (!this.data.recordFilePath) {
            wx.showToast({ title: '请先录制录音', icon: 'none' });
            return;
        }
        wx.uploadFile({
            filePath: this.data.recordFilePath,
            name: 'audio_data',
            url: baseUrl + '/recognize',
            formData: {},
            header: { 'content-type': 'multipart/form-data' },
            success: function (res) {
                try {
                    const responseData = JSON.parse(res.data);
                    if (responseData.code === 200 && responseData.text) {
                        this.setData({
                            editableContent: responseData.text
                        });
                        // 调用函数将识别结果发送到另一个端口
                        this.sendRecognitionResultToServer(responseData.text).then(() => {
                            // 这里可以添加成功发送后的其他逻辑，比如提示用户等
                            wx.showToast({
                                title: '识别结果已成功发送到其他端口',
                                icon: 'success',
                                duration: 2000
                            });
                        }).catch(err => {
                            console.log('发送识别结果到其他端口失败:', err);
                            wx.showToast({
                                title: '识别结果发送到其他端口失败，请稍后重试',
                                icon: 'none',
                                duration: 2000
                            });
                        });
                    } else {
                        wx.showToast({
                            title: responseData.message || '识别出现其他错误',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                } catch (e) {
                    console.log('无法解析识别结果：', e);
                    console.log('接收到的原始返回数据：', res.data);
                }
            }.bind(this),
            fail: function (err) {
                console.log('上传失败，详细错误信息：', err);
                if (err.errMsg.includes('network')) {
                    wx.showToast({
                        title: '网络连接出现问题，请检查网络设置后重试',
                        icon: 'none',
                        duration: 2000
                    });
                } else if (err.errMsg.includes('file')) {
                    wx.showToast({
                        title: '文件相关错误，请检查音频文件是否正常',
                        icon: 'none',
                        duration: 2000
                    });
                } else {
                    wx.showToast({
                        title: '上传出现其他未知错误，请稍后重试',
                        icon: 'none',
                        duration: 2000
                    });
                }
            }
        });
    },
    // 发送识别结果到另一个端口的函数，确保以JSON格式发送
    sendRecognitionResultToServer(result) {
        const resultToSend = {
            text: result
        };
        return new Promise((resolve, reject) => {
            const options = {
                url: 'http://localhost:8088/files/files/fillData',
                method: 'POST',
                header: {
                    'content-type': 'application/json' // 设置请求头为JSON格式
                },
                data: {}
            };
            try {
                options.data = JSON.stringify(resultToSend); // 对要发送的数据进行JSON序列化
            } catch (jsonError) {
                console.log('JSON序列化识别结果失败:', jsonError);
                reject('识别结果数据格式错误');
                return;
            }
            http.request(options).then(res => {
                if (res.data && res.data.code === 200) {
                    console.log('识别结果已成功发送到服务器');
                    resolve();
                } else {
                    console.log('发送识别结果到服务器失败', res);
                    reject('发送识别结果到服务器失败');
                }
            }).catch(err => {
                console.log('发送识别结果到服务器请求失败', err);
                reject(err);
            });
        });
    }
  });